import pytest
from common.request_util_test import RequestUtil
from common.test_yaml_util_test import YamlUtil
from config import datas
import time


class TestPluginManagement:
    # 0表示之前未安装datas.test_plugin_management["plugin_name"]指定的扩展组件，需要临时安装，并在最后一个用例卸载；
    # 1表示之前已安装，无需单独安装和卸载。且测试过程不能修改/删除原有的扩展组件。
    flag_test_plugin_installed_stat = 0

    @pytest.mark.parametrize('yaml', YamlUtil().read_testcase_yaml(
        'v24.09/pluginManagement/POST_change_consoleplugin_web_enabled_stat.yaml'))
    def test_change_consoleplugin_web_enabled_stat(self, yaml):
        # 更改扩展界面启用状态
        # 尝试在已安装的扩展组件中寻找datas.test_plugin_management["plugin_name"]。如果已安装，则将flag置1；如果未安装则保持0不变
        uri_tmp = "/clusters/host/rest/application-management/v1beta1/helm-releases?extension=true"
        url_tmp = datas.baseUrl + uri_tmp
        method_tmp = "GET"
        headers_tmp = {"Content-Type": "application/json"}
        req_tmp = RequestUtil().send_request(method_tmp, url_tmp, headers=headers_tmp)
        req_tmp = req_tmp.json()  # 将返回信息读取为json格式。如果是content()则会读取为bytes类型数据
        for i in req_tmp["data"]["items"]:
            if i["name"] == datas.test_plugin_management["plugin_name"]:
                TestPluginManagement.flag_test_plugin_installed_stat = 1
                # print("\nplugin_name已存在，无需单独安装")
                break
            else:
                continue
        # 如果在已安装扩展组件中未找到datas.test_plugin_management["plugin_name"]指定的扩展组件，则需要单独安装
        if TestPluginManagement.flag_test_plugin_installed_stat == 0:
            # print("\n临时monitoring-dashboard不存在，开始安装...")
            uri_plugin_install = "/rest/application-management/v1beta1/helm-releases/namespace/{namespace}/release/{release}"
            uri_plugin_install = uri_plugin_install.replace("{namespace}", datas.test_plugin_management["namespace"])
            uri_plugin_install = uri_plugin_install.replace("{release}", datas.test_plugin_management["plugin_name"])
            uri_plugin_install = datas.baseUrl + uri_plugin_install
            method_plugin_install = "POST"
            headers_plugin_install = {"Content-Type": "application/json"}
            data_plugin_install = {
                "chartName": datas.test_plugin_management["plugin_name"],
                "repoName": datas.test_plugin_management["repoName"],
                "version": datas.test_plugin_management["version"],
                "values": datas.test_plugin_management["values"],
            }
            req_plugin_install = RequestUtil().send_request(method_plugin_install, uri_plugin_install,
                                                            headers=headers_plugin_install, json=data_plugin_install)
            assert req_plugin_install.status_code == 202
            # print("\n临时monitoring-dashboard安装成功")
        # 更改前台启停状态（不论之前状态如何，均置为datas.test_plugin_management["enabled"]配置的状态）
        uri = yaml['request']['url'].replace("{pluginName}", datas.test_plugin_management["plugin_name"])
        url = datas.baseUrl + uri
        method = yaml['request']['method']
        headers = yaml['request']['headers']
        data = yaml['request']['data']
        data["pluginName"] = datas.test_plugin_management["plugin_name"]
        data["enabled"] = datas.test_plugin_management["enabled"]
        req = RequestUtil().send_request(method, url, headers=headers, json=data)
        assert req.status_code == yaml['validate'][0]['equals']['status_code']
        # 如果是当前class安装了扩展组件，则需要卸载上面安装的扩展组件（详见当前class最后一个用例）

    @pytest.mark.parametrize('yaml',
                             YamlUtil().read_testcase_yaml('v24.09/pluginManagement/GET_get_consoleplugin_list.yaml'))
    def test_get_consoleplugin_list(self, yaml):
        # 获取ConsolePlugin列表
        uri = yaml['request']['url']
        url = datas.baseUrl + uri
        method = yaml['request']['method']
        headers = yaml['request']['headers']
        data = yaml['request']['data']
        req = RequestUtil().send_request(method, url, headers=headers, json=data)
        assert req.status_code == yaml['validate'][0]['equals']['status_code']

    @pytest.mark.parametrize('yaml', YamlUtil().read_testcase_yaml(
        'v24.09/pluginManagement/GET_get_consoleplugin_web_enabled_stat.yaml'))
    def test_get_consoleplugin_web_enabled_stat(self, yaml):
        # 获取指定ConsolePlugin对应扩展界面的启用状态
        uri = yaml['request']['url'].replace("{pluginName}", datas.test_plugin_management["plugin_name"])
        url = datas.baseUrl + uri
        method = yaml['request']['method']
        headers = yaml['request']['headers']
        data = yaml['request']['data']
        req = RequestUtil().send_request(method, url, headers=headers, json=data)
        assert req.status_code == yaml['validate'][0]['equals']['status_code']

    @pytest.mark.parametrize('yaml', YamlUtil().read_testcase_yaml(
        'v24.09/pluginManagement/GET_get_specefied_consoleplugin.yaml'))
    def test_get_specefied_consoleplugin(self, yaml):
        # 获取单个ConsolePlugin资源
        uri = yaml['request']['url'].replace("{pluginName}", datas.test_plugin_management["plugin_name"])
        url = datas.baseUrl + uri
        method = yaml['request']['method']
        headers = yaml['request']['headers']
        data = yaml['request']['data']
        req = RequestUtil().send_request(method, url, headers=headers, json=data)
        assert req.status_code == yaml['validate'][0]['equals']['status_code']
        # 卸载第1个用例中安装的扩展组件，保证环境不产生冗余数据
        if TestPluginManagement.flag_test_plugin_installed_stat == 0:
            uri_plugin_delete = "/clusters/host/rest/application-management/v1beta1/helm-releases/namespace/{namespace}/release/{release}"
            uri_plugin_delete = uri_plugin_delete.replace("{namespace}", datas.test_plugin_management["namespace"])
            uri_plugin_delete = uri_plugin_delete.replace("{release}", datas.test_plugin_management["plugin_name"])
            url_plugin_delete = datas.baseUrl + uri_plugin_delete
            method_plugin_delete = "DELETE"
            headers_plugin_delete = {"Content-Type": "application/json"}
            req_plugin_delete = RequestUtil().send_request(method_plugin_delete, url_plugin_delete,
                                                           headers=headers_plugin_delete)
            assert req_plugin_delete.status_code == 200
            # print("\n临时plugin使用完毕，已卸载成功")
            flag_time = 0  # 防止死循环
            url_try = datas.baseUrl + "/clusters/host/rest/monitoring-dashboard/v1beta1/dashboards"
            while 1:
                req_try = RequestUtil().send_request("GET", url_try)
                if req_try.status_code == 200:
                    time.sleep(1)
                    flag_time += 1
                    if flag_time >= 30:
                        print("ERR: monitoring-dashboard扩展组件在30s仍未卸载完毕，请手动排查并卸载")
                        break
                    continue
                elif req_try.status_code == 404:
                    # print("monitoring-dashboard扩展组件卸载成功。共耗时:", flag_time, "秒")
                    break
                else:
                    print("ERR: 出现预期之外的状态码:", req_try.status_code, "请手工排查")
            time.sleep(20)  # 必须预留充足的时间等待helm卸载完毕
